import request from './request';
import cj from '@/node_modules/crypto-js/crypto-js.js';
// import util from '@/utils/util.js';

// 设置全局配置
let baseURL;
if (process.env.NODE_ENV === 'development') {
	baseURL = 'https://sidong-dev.speedmin.com/api/';
} else {
	baseURL = 'https://sidong.speedmin.com/api/';
}

request.prototype.setConfig({
	url: baseURL,
	header: {
		'X-Requested-With': 'XMLHttpRequest'
	}
});

// 全局拦截器
request.prototype.addGlobalInterce({
	// 请求拦截器 (例如配置token)
	request(config) {
		if (uni.getStorageSync('token')) {
			config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token');
		}
		if (uni.getAccountInfoSync().miniProgram.appId) {
			config.header['signid'] = cj.MD5(uni.getAccountInfoSync().miniProgram.appId).toString();
		}
		return config;
	},
	// 响应拦截器 (例如根据状态码拦截数据)
	response(res) {
		const code = res.data.code;
		const data = res.data.data;
		const message = res.data.message;
		if (code !== 0) {
			uni.showModal({
				title: '提示',
				content: message,
				showCancel: false
			});
			uni.hideLoading();
			return Promise.reject(new Error(message || 'Error'))
		}
		uni.hideLoading();
		return res.data;
	}
});

export default request
